// utils/streamChat.js
export async function* getStreamingResponse(message, sessionId) {
  return new Promise((resolve, reject) => {
    const requestTask = uni.request({
      url: 'http://localhost:8081/api/chat/send',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': uni.getStorageSync('token'),
        'User-Id': uni.getStorageSync('userId')
      },
      data: {
        message,
        sessionId
      },
      enableChunked: true, // 启用分块传输
      success: (res) => {
        try {
          const chunks = res.data.split('\n');
          for (const chunk of chunks) {
            if (chunk.startsWith('data: ')) {
              const json = JSON.parse(chunk.slice(5));
              if (chunk.includes('[DONE]')) {
                resolve();
                break;
              }
              if (json.choices?.[0]?.delta?.content) {
                resolve({
                  id: json.id,
                  content: json.choices[0].delta.content,
                  role: 'assistant',
                  timestamp: Date.now()
                });
              }
            }
          }
        } catch (e) {
          console.error('Error parsing response:', e);
          reject(e);
        }
      },
      fail: reject
    });

    // 监听数据块接收
    requestTask.onChunkReceived((response) => {
      try {
        const chunk = response.data;
        if (chunk.startsWith('data: ')) {
          const json = JSON.parse(chunk.slice(5));
          if (json.choices?.[0]?.delta?.content) {
            resolve({
              id: json.id,
              content: json.choices[0].delta.content,
              role: 'assistant',
              timestamp: Date.now()
            });
          }
        }
      } catch (e) {
        console.error('Error parsing chunk:', e);
      }
    });
  });
}